﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using DAL;
using UtilityExtensions;
using BOL;
using BOL.UI;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;

namespace UILGestion.Admin.UILocalizacion
{
    public partial class UIItemEditGrid : System.Web.UI.UserControl
    {

        public  UIItemEditGrid()
        {

            _db = new dbGestionDataContext(Parametros.strConnString);
        }

        private dbGestionDataContext _db;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {

                idLocalizacion.Value = (string)Request.QueryString["id"];
                FormatForm();
            }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
            
            
        }
       
        
        private void FormatForm()
        {
                BindDataItem();
                setFooterRow();
        }


        protected void AddItem(object sender, EventArgs e)
        {
            try
            {


                TextBox AdicionTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("AdicionTXT"));

                DropDownList tipoUI =
                    ((DropDownList)itemGridView.FooterRow.FindControl("descripcionDDL"));
                              



                var bloque = new UIBL();
                bloque.GenerarUI(_db, tipoUI.SelectedValue.ToInt(), AdicionTXT.Text.ToInt(),idLocalizacion.Value.ToInt());

                DbUtil.Db.SubmitChanges();
                BindDataItem();
                setFooterRow();
                GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                int idTipoUI = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());


                TextBox adicionTXT =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("adicionTXT"));


                var ui = new UIBL();
                ui.GenerarUI(_db, idTipoUI, adicionTXT.Text.ToInt(),idLocalizacion.Value.ToInt());
                
               
                gv.EditIndex = -1;

                BindDataItem();
                setFooterRow();
                 GridUpdatePanel.Update();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = e.NewEditIndex;

                BindDataItem();
                itemGridView.FooterRow.Visible = false;
                GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = -1;
                BindDataItem();
                GridUpdatePanel.Update();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
       

        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<UIGroupInfo> itemList0 = new List<UIGroupInfo>();
                UIGroupInfo itemcero = new UIGroupInfo();
                itemcero.idInternal = 0;
                itemcero.formulario = "";

                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }

        public void BindDataItem()
        {
            var listaUI=DbUtil.Db.Menus.Single(p=>p.idInternal==73);

            var q = from a in DbUtil.Db.UIs
                    where a.idLocalizacion == idLocalizacion.Value.ToInt()
                    group a by new { a.idTipoUI } into g
                    select new UIGroupInfo
                    {
                        idInternal = g.First().idTipoUI,
                        descripcion = g.First().UITipo.descripcion,
                        actual = g.Count(),
                        adicion = 0 ,
                        formulario=string.Format("javascript:loadTabFromForm('tab{0}-{1}','{2}','{3}?idLocalizacion={4}&idEtapa={5}&idtipoUI={6}&idProyecto={1}');",
                                    listaUI.idAplicacion,
                                    g.First().Etapa.idProyecto,//proy
                                    g.First().Etapa.Proyecto.descripcion,
                                    listaUI.url,
                                    g.First().idLocalizacion,
                                    g.First().idEtapa,
                                     g.First().idTipoUI)
                                    
                         
                    };


                    


            itemGridView.DataSource = q;
            itemGridView.DataBind();
            resetEmpty();

        }

        private void setFooterRow()
        {

            var qui= (from a in DbUtil.Db.UIs
                     where a.idLocalizacion == idLocalizacion.Value.ToInt()
                     select a.idTipoUI).Distinct().ToList();

            var uiTipo =from p in DbUtil.Db.UITipos
                        where !qui.Contains(p.idInternal)
                            select p;

            DropDownList obraInsertDropDownList = ((DropDownList)itemGridView.FooterRow.FindControl("descripcionDDL"));
            
            obraInsertDropDownList.DataValueField = "idInternal";
            obraInsertDropDownList.DataTextField = "descripcion";
            obraInsertDropDownList.DataSource = uiTipo;
            obraInsertDropDownList.DataBind();



        }



       
    }

}